<template>
  <div>
    <h3>商品分类</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加分类按钮区域 -->
      <el-row>
        <el-col :span="12">
          <!-- <el-select v-model="queryInfo.type" placeholder="请选择">
            <el-option
              v-for="item in type"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select> -->

          <el-button type="primary" class="btn" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 分类表格  -->

      <!-- 分类表格
:data(设置数据源) :columns(设置表格中列配置信息) :selection-type(是否有复选框)
:expand-type(是否展开数据) show-index(是否设置索引列) index-text(设置索引列头)
border(是否添加纵向边框) :show-row-hover(是否鼠标悬停高亮) -->

      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效区域， 设置对应的模板列： slot="isok"(与columns中设置的template一致) -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color:lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0" type="primary"
            >一级</el-tag
          >
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag
            size="mini"
            type="warning"
            v-else-if="scope.row.cat_level === 2"
            >三级</el-tag
          >
          <el-tag size="mini" type="info" v-else
            >{{ scope.row.cat_level + 1 }}级</el-tag
          >
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeCateFn(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page.sync="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRuleForm"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="cat_pid">
          <!-- expandTrigger='hover'(鼠标悬停触发级联) v-model(设置级联菜单绑定数据) :options(指定级联菜单数据源)  :props(用来配置数据显示的规则)
  clearable(提供“X”号完成删除文本功能) change-on-select(是否可以选中任意一级的菜单) -->

          <el-cascader
            expandTrigger="hover"
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog
      :title="'编辑分类 - [ID:' + editForm.id + ']'"
      :visible.sync="editFlag"
      width="50%"
      :show-close="false"
    >
      <el-form
        :model="editForm"
        :rules="addCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEditFormFn">取 消</el-button>
        <el-button type="primary" @click="editSaveFn('editCateFormRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCateListAPI,
  addCateListAPI,
  deleteCateByIdAPI,
  editCateByIdAPI
} from '@/api'
export default {
  data() {
    return {
      // 商品分类数据列表
      cateList: [],
      // 查询分类数据的条件
      queryInfo: {
        type: 6,
        pagenum: 1,
        pagesize: 10
      },
      type: [
        { id: 1, label: '一级' },
        { id: 2, label: '二级' },
        { id: 3, label: '三级' }
      ],
      // 保存总数据条数
      total: 0,
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        {
          label: '是否有效',
          prop: '',
          type: 'template',
          template: 'isok',
          width: 100
        },
        {
          label: '排序',
          prop: '',
          type: 'template',
          template: 'order',
          width: 100
        },
        { label: '操作', prop: '', type: 'template', template: 'opt' }
      ],
      addCateDialogVisible: false,
      addCateForm: {
        cat_name: '', // 添加分类的父级id，0则表示父级为0.添加一级分类
        cat_pid: 0,
        // 添加分类的等级，0则表示添加一级分类
        cat_level: 0
      },
      // 添加分类校验规则
      addCateFormRules: {
        // 验证规则
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      parentCateList: [],
      // 配置级联菜单中数据如何展示
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      // 绑定用户选择的分类值
      selectedKeys: [],
      editFlag: false,
      editForm: {
        id: -1,
        cat_name: ''
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    async getCateList() {
      //   console.log(this.queryInfo) // this.xxx => 包含许多vue添加的属性+方法用于获取对象的属性
      //   console.log({ ...this.queryInfo }) // {...this.xxx} => 把对象进行解构，vue实例天津的属性+方法去掉： {"type": 2, "pagenum": 1,"pagesize": 0}
      // console.log(...this.queryInfo)
      // 获取商品分类数据

      //   const { data: res } = await getCateListAPI({ params: this.queryInfo }) ==> axios get请求时设置params属性 ，接口解析不到相应的参数，会把所有数据都返回

      const { data: res } = await getCateListAPI({ ...this.queryInfo })

      //   console.log(res)

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表数据失败')
      }
      // 将数据列表赋值给cateList
      this.cateList = res.data.result
      // 保存总数据条数
      this.total = res.data.total
      //   console.log(res.data);
    },
    async getParentCateList() {
      // 获取父级分类数据列表
      const { data: res } = await getCateListAPI({ type: 4 })

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表数据失败')
      }
      this.parentCateList = res.data
    },
    showAddCateDialog() {
      this.addCateDialogVisible = true
      this.getParentCateList()
    },
    parentCateChange() {
      // 级联菜单中选择项发生变化时触发
      //   console.log(this.selectedKeys)
      // 如果用户选择了父级分类
      if (this.selectedKeys.length > 0) {
        // 则将数组中的最后一项设置为父级分类
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        // level也要跟着发生变化
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    addCateDialogClosed() {
      // 当关闭添加分类对话框时，重置表单
      this.addCateDialogVisible = false
      this.$refs.addCateFormRuleForm.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    addCate() {
      // 点击确定，完成添加分类
      // console.log(this.addCateForm)
      this.$refs.addCateFormRuleForm.validate(async valid => {
        if (!valid) return
        // 发送请求完成添加分类
        const { data: res } = await addCateListAPI({ ...this.addCateForm })

        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }

        this.$message.success('添加分类成功')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    async removeCateFn(id) {
      const result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      if (result === 'cancal') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }

      const { data: res } = await deleteCateByIdAPI(id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getCateList()
    },
    showEditDialog(row) {
      // console.log(row)
      this.editForm.id = row.cat_id
      this.editForm.cat_name = row.cat_name
      this.editFlag = true
    },
    resetEditFormFn() {
      this.editForm.id = -1
      this.editForm.cat_name = ''
      this.editFlag = false
    },
    editSaveFn(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        const { data: res } = await editCateByIdAPI({
          ...this.editForm
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

        this.$message({
          message: res.meta.msg,
          type: 'success'
        })
        this.resetEditFormFn(formName)
        this.getCateList()
      })
    }
  }
}
</script>

<style scoped>
.btn {
  margin-left: 10px;
  margin-bottom: 10px;
}

.el-cascader {
  width: 100%;
}
</style>
